package com.sam.im.heiqun.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.model.CityModel;
import com.sam.im.heiqun.entities.model.DistrictModel;
import com.sam.im.heiqun.entities.model.ProvinceModel;
import com.sam.im.heiqun.service.XmlParserHandler;
import com.sam.im.heiqun.uis.widgets.OnWheelChangedListener;
import com.sam.im.heiqun.uis.widgets.WheelView;
import com.sam.im.heiqun.uis.widgets.adapters.ArrayWheelAdapter;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Created by Martin on 2017/1/11.
 */

public class CitySelectUtil implements OnWheelChangedListener, View.OnClickListener {

    private Context mContext;
    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName = "";

    /**
     * 当前区的邮政编码
     */
    protected String mCurrentZipCode = "";

    /**
     * 解析省市区的XML数据
     */

    Dialog lxDialog;

    private WheelView mViewProvince;
    private WheelView mViewCity;
    private TextView cancel;
    private TextView commit;
    private static int type = 0 ;//1- 是钱包明细来的

    private static IOnCitySelectListener listener;


    protected void initProvinceDatas() {
        List<ProvinceModel> provinceList = null;
        AssetManager asset = mContext.getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            // 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            // 获取解析出来的数据
            provinceList = handler.getDataList();

            //*/ 初始化默认选中的省、市、区
            if (provinceList != null && !provinceList.isEmpty()) {
                mCurrentProviceName = provinceList.get(0).getName();
                List<CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList != null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<DistrictModel> districtList = cityList.get(0).getDistrictList();
                    mCurrentDistrictName = districtList.get(0).getName();
                    mCurrentZipCode = districtList.get(0).getZipcode();
                }
            }
            //*/
            mProvinceDatas = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getName();
                List<CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<DistrictModel> districtList = cityList.get(j).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k = 0; k < districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
                        mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void showCitySelectDialog(Context context, IOnCitySelectListener listener) {
        CitySelectUtil.listener = listener;
        CitySelectUtil citySelectUtil = new CitySelectUtil();
        citySelectUtil.showLeixingDialog(context);
    }
    public static void showCitySelectDialog1(Context context, IOnCitySelectListener listener) {
        type = 1 ;
        CitySelectUtil.listener = listener;
        CitySelectUtil citySelectUtil = new CitySelectUtil();
        citySelectUtil.showLeixingDialog(context);
    }
    public static void showWalletTimeDialog(Context context, IOnCitySelectListener listener, String[] datas1, Map<String, String[]> datas2) {
        type = 1 ;
        CitySelectUtil.listener = listener;
        CitySelectUtil citySelectUtil = new CitySelectUtil();
        citySelectUtil.showWalletTimeDialog(context,datas1,datas2);
    }

    public static void showOverseasSelectDialog(Context context, IOnCitySelectListener listener) {
        CitySelectUtil.listener = listener;
        CitySelectUtil citySelectUtil = new CitySelectUtil();
        citySelectUtil.showOverseasDialog(context);
    }

    /**
     * 钱包明细，选择时间
     */
    public void showWalletTimeDialog(Context context, String[] datas1, Map<String, String[]> datas2) {

        mContext = context;
        // TODO Auto-generated method stub
        lxDialog = new Dialog(mContext, R.style.CitySelectDialog);
        lxDialog.setCancelable(false);
        lxDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        lxDialog.setContentView(R.layout.city_select);

        setUpViews();
        setUpListener();
        setWalletTimeData(datas1, datas2);

        Window window = lxDialog.getWindow();
        assert window != null;
        window.setGravity(Gravity.BOTTOM);
        WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = dm.widthPixels;
        window.setAttributes(lp);
        lxDialog.show();
    }
    /**
     * 国内地区选择器
     */
    public void showLeixingDialog(Context context) {
        try{
        mContext = context;
        // TODO Auto-generated method stub
        lxDialog = new Dialog(mContext, R.style.CitySelectDialog);
        lxDialog.setCancelable(false);
        lxDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        lxDialog.setContentView(R.layout.city_select);

        setUpViews();
        setUpListener();
        setUpData();

        Window window = lxDialog.getWindow();
        assert window != null;
        window.setGravity(Gravity.BOTTOM);
        WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = dm.widthPixels;
        window.setAttributes(lp);
        lxDialog.show();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 国外地区选择器
     */
    public void showOverseasDialog(Context context) {
        mContext = context;
        lxDialog = new Dialog(mContext, R.style.CitySelectDialog);
        lxDialog.setCancelable(false);
        lxDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        lxDialog.setContentView(R.layout.select_over_seas);

        mViewProvince = (WheelView) lxDialog.findViewById(R.id.id_province);
        cancel = (TextView) lxDialog.findViewById(R.id.cancel);
        commit = (TextView) lxDialog.findViewById(R.id.commit);

        mViewProvince.addChangingListener(this);
        cancel.setOnClickListener(this);
        commit.setOnClickListener(this);

        mProvinceDatas = new String[]{context.getString(R.string.chain), "U.S.A", context.getString(R.string.korea), context.getString(R.string.japan)};
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<>(mContext, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);

        Window window = lxDialog.getWindow();
        assert window != null;
        window.setGravity(Gravity.BOTTOM);
        WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = dm.widthPixels;
        window.setAttributes(lp);
        lxDialog.show();
    }


    private void setUpViews() {

        mViewProvince = (WheelView) lxDialog.findViewById(R.id.id_province);
        mViewCity = (WheelView) lxDialog.findViewById(R.id.id_city);

        cancel = (TextView) lxDialog.findViewById(R.id.cancel);
        commit = (TextView) lxDialog.findViewById(R.id.commit);
    }

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);

        cancel.setOnClickListener(this);
        commit.setOnClickListener(this);
    }

    private void setUpData() {
        initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(mContext, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        updateCities();
        updateAreas();
    }
    private void setWalletTimeData(String[] datas1, Map<String, String[]> datas2) {

        mProvinceDatas = datas1;
        mCitisDatasMap = datas2;

        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(mContext, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        updateCities();
        updateAreas();
    }


    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        try{
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(mContext, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        if (null==mCitisDatasMap)return;
        if (null==mCitisDatasMap.get(mCurrentProviceName))return;
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
    }


    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
// TODO Auto-generated method stub
        if (isZh()) {
            if (wheel == mViewProvince) {
                updateCities();
            } else if (wheel == mViewCity) {
                updateAreas();
            }
        } else {

        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                lxDialog.dismiss();
                break;
            case R.id.commit:
                if (listener != null) {
                    if (isZh()) {
                        listener.onCitySelect(mCurrentProviceName, mCurrentCityName);
                    } else {
                        int i = mViewProvince.getCurrentItem();
                        listener.onCitySelect(mProvinceDatas[i], null);

                    }
                }
                lxDialog.dismiss();
                break;
        }
    }

    public interface IOnCitySelectListener {
        void onCitySelect(String province, String city);
    }


    private boolean isZh() {
        Locale locale = mContext.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh") || 1==type)
            return true;
        else
            return false;
    }


}
